//
//  DataService.m
//  HousingPoliceAssistant
//
//  Created by 云警01 on 2019/6/6.
//  Copyright © 2019 盛洋. All rights reserved.
//

#import "DataService.h"

static DataService *_dataService = nil;

@interface DataService (){
    
}

@end

@implementation DataService

+ (DataService*)sharedService{
    @synchronized(self){
        if(!_dataService){
            _dataService = [[DataService alloc] init];
        }
    }
    return _dataService;
}

- (BOOL)isFirstStart{
    
    BOOL isF = [[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"];
    
    if(!isF){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
    }
    
    return isF;
}

-(BOOL)isFromAps:(NSDictionary*)launchOptions{
    if (launchOptions) {
        NSDictionary* pushNotificationKey = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        if (pushNotificationKey) {
            
            if ([pushNotificationKey objectForKey:@"aps"]!=NULL) {
                return YES;
            }else{
                return NO;
            }
            
            
        }else{
            return NO;
        }
    }else{
        return NO;
    }
    
}
- (NSString*)getUUID{
    return Uuid;
}
//清除本地证书
-(void)clearCert{
    
    NSUDSetValueWithKey(@"", @"app_dc");
    GMLog("Cert Clear:%@",NSUDGetValueWithKey(@"app_dc"));
}

+(NSString *)intervalSinceNow: (NSString *) pubString
{
    NSArray *array = [pubString componentsSeparatedByString:@"."];
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //    NSDate* endDate = [NSDate date];
    NSDate* startDate = [dateFormat dateFromString:array[0]];
    
    //读取服务器返回的时间
    double seconds = [NSUDGetValueWithKey(@"app_time") doubleValue];
    NSDate *nowDate = [NSDate dateWithTimeIntervalSince1970:seconds/(double)1000.0];
    //计算第一天0点时间
    NSUInteger flags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit
    | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    NSDateComponents *parts = [[NSCalendar currentCalendar] components:flags fromDate:nowDate];
    [parts setHour:0];
    [parts setMinute:0];
    [parts setSecond:0];
    NSDate *beginningDay = [[NSCalendar currentCalendar] dateFromComponents:parts];
    
    
    NSTimeInterval timeInterval = [startDate timeIntervalSince1970];
    NSTimeInterval timeIntervalNow = [beginningDay timeIntervalSince1970];
    
    NSTimeInterval cha = timeInterval - timeIntervalNow;
    
    if (cha >= 0) {
        return @"今日";
    } else {
        NSString *dayString;
        
        if (fabs(cha) <= 86400.0) {
            dayString = @"昨日";
        } else {
            [dateFormat setDateFormat:@"MM-dd"];
            dayString = [dateFormat stringFromDate:startDate];
        }
        return dayString;
    }
}
/**
 *  时间格式转换
 *
 *  @param pubString yyyy-MM-dd HH:mm:ss
 *
 *  @return 昨天，今天，时间
 */
+(NSString *)timeYearMonthDay: (NSString *) pubString
{
    NSString *dayString = [[pubString componentsSeparatedByString:@" "] objectAtIndex:0];
    return dayString;
}

+(NSString *)intervalSinceNowForReview: (NSString *) pubString
{
    NSArray *array = [pubString componentsSeparatedByString:@"."];
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
    [dataFormatter setTimeZone:[NSTimeZone localTimeZone]];
    [dataFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *date = [dataFormatter dateFromString:array[0]];
    
    //读取服务器返回的时间
    double seconds = [NSUDGetValueWithKey(@"app_time") doubleValue];
    
    const static NSTimeInterval oneDay = 24.0*3600.0;
    const static NSTimeInterval oneHour = 3600.0;
    const static NSTimeInterval oneMinute = 60.0;
    NSTimeInterval sub = fabs([date timeIntervalSince1970] - seconds/1000);
    if (sub < oneMinute) {
        return @"刚刚";
    } else if (sub < oneHour) {
        return [NSString stringWithFormat:@"%d分钟前",(int)(sub/oneMinute)];
    } else if (sub < oneDay) {
        return [NSString stringWithFormat:@"%d小时前",(int)(sub/oneHour)];
    } else {
        return [[pubString componentsSeparatedByString:@" "] objectAtIndex:0];
    }
}

+(NSString *)intervalSinceNowForPhotoLive:(NSString *)pubString
{
    NSArray *array = [pubString componentsSeparatedByString:@"."];
    NSDateFormatter *dataFormatter = [[NSDateFormatter alloc] init];
    [dataFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [dataFormatter setDateFormat:@"yy-MM-dd HH:mm:ss"];
    NSDate *date = [dataFormatter dateFromString:array[0]];
    
    
    NSDate *today = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: today];
    NSDate *localeDate = [today  dateByAddingTimeInterval: interval];
    
    // 10 first characters of description is the calendar date:
    NSString * todayString = [[localeDate description] substringToIndex:10];
    NSString * dateString = [[date description] substringToIndex:10];
    
    if ([dateString isEqualToString:todayString]){
        [dataFormatter setDateFormat:@"HH:mm"];
        NSString *  locationString=[dataFormatter stringFromDate:date];
        return locationString;
    }else{
        [dataFormatter setDateFormat:@"yy-MM-dd"];
        NSString *  locationString=[dataFormatter stringFromDate:date];
        return locationString;
    }
    
    //    //读取服务器返回的时间
    //    double seconds = [NSUDGetValueWithKey(@"app_time") doubleValue];
    //
    //    const static NSTimeInterval oneDay = 24.0*3600.0;
    //    NSTimeInterval sub = fabs([date timeIntervalSince1970] - seconds/1000);
    //    if (sub < oneDay) {
    //        [dataFormatter setDateFormat:@"HH:mm"];
    //        NSString *  locationString=[dataFormatter stringFromDate:date];
    //        return locationString;
    //    } else {
    //        return [[pubString componentsSeparatedByString:@" "] objectAtIndex:0];
    //    }
    
}

+(NSString *)formatDate:(NSString *)pubString {
    return [DataService formatDate:pubString formatString:@"MM-dd HH:mm"];
}

+(NSString *)formatDate:(NSString *)pubString formatString:(NSString *)formatString {
    NSArray *array = [pubString componentsSeparatedByString:@"."];
    NSDateFormatter *dateFormat=[[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate* newDate = [dateFormat dateFromString:array[0]];
    [dateFormat setDateFormat:formatString];
    NSString *dateString =[dateFormat stringFromDate:newDate];
    //NSLog(dateString);
    return dateString;
}

+ (NSString *)dateToString:(NSDate *)date format:(NSString *)format
{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterFullStyle];
    [dateFormatter setDateFormat:format];
    NSString *dateString = [dateFormatter stringFromDate:date];
    return dateString;
}

//输入的日期字符串形如：@"1992-05-21 13:08:08"
+ (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *fromdate=[format dateFromString:dateString];
    
    //注意:这里获取的时间要通过时区然后再转换为NSDate，不然转换为NSDate后和获取的字符串类型的日期 不一样
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *returnDate = [fromdate  dateByAddingTimeInterval: frominterval];
    NSLog(@"returnDate=%@",returnDate);
    return returnDate;
}

+ (NSString *)formatNumber:(int)number {
    if (number < 100000) {
        return [NSString stringWithFormat:@"%d", number];
    } else {
        return @"99999+";
    }
}

+(NSString *)stringToDate:(NSString *)dateNum{
    
    //        //dateNum是服务器返回的13位时间戳
    //        // iOS 生成的时间戳是10位
    //        NSTimeInterval interval    = [dateNum doubleValue];
    //        NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    //        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //        //[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //        [formatter setDateFormat:@"yyyy-MM-dd"];
    //        NSString *dateString  = [formatter stringFromDate: date];
    //    return dateString;
    
    if ([dateNum CheckNSStringData] && dateNum.length > 2) {
        double time = [dateNum doubleValue];
        NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:time];
        NSDateFormatter *formatter = [NSDateFormatter new];
        [formatter setDateFormat:@"HH:mm"];
        NSString *timeS = [formatter stringFromDate:myDate];
        return timeS;
    }else {
        return @"";
    }
}

- (NSString *)getTimeFromTimesTamp:(NSString *)timeStr format:(NSString *)myformat
{
    double time = [timeStr doubleValue];
    NSDate *myDate = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [NSDateFormatter new];
    [formatter setDateFormat:myformat];
    NSString *timeS = [formatter stringFromDate:myDate];
    return timeS;
}

#pragma mark - 地理信息相关
//获取区的位置编码
+(NSString*)convertNameToCode:(NSString *)province city:(NSString *)city district:(NSString *)district
{
    NSString *dataStr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"city2code.js" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
    NSData *resData = [[NSData alloc] initWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding]];
    
    NSArray *jsonAllData = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
    
    NSString *provinceCode = nil;
    NSString *cityCode = nil;
    NSString *districtCode = nil;
    
    //先遍历找到省
    NSArray *provinceArray = [jsonAllData objectAtIndex:0];
    for (NSDictionary *dic in provinceArray) {
        if ([[dic objectForKey:@"name"] isEqualToString:province]) {
            provinceCode = [dic objectForKey:@"code"];
            break;
        }
    }
    if (!provinceCode) {
        return nil;
    }
    //遍历市
    NSDictionary *citysDic = [jsonAllData objectAtIndex:1];
    NSArray *citysArray = [citysDic objectForKey:provinceCode];
    for (NSDictionary *cityDic in citysArray) {
        //手机定位的名字可能是：北京市市辖区
        if ([city rangeOfString:[cityDic objectForKey:@"name"]].length > 0) {
            cityCode = [cityDic objectForKey:@"code"];
            break;
        }
    }
    if (!cityCode) {
        return provinceCode;
    }
    //遍历区
    if (!district) {
        return cityCode;
    }
    NSDictionary *countysDic = [jsonAllData objectAtIndex:2];
    NSArray *countysArray = [countysDic objectForKey:cityCode];
    for (NSDictionary *countyDic in countysArray) {
        if ([[countyDic objectForKey:@"name"] isEqualToString:district]) {
            districtCode = [countyDic objectForKey:@"code"];
            break;
        }
    }
    if (!districtCode) {
        return cityCode;
    }
    return districtCode;
}
//获取全国省市区信息
- (NSArray *)gProvinceCityDistrictData
{
    if (!_gProvinceCityDistrictData) {
        NSString *dataStr = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"city2code.js" ofType:nil] encoding:NSUTF8StringEncoding error:nil];
        NSData *resData = [[NSData alloc] initWithData:[dataStr dataUsingEncoding:NSUTF8StringEncoding]];
        
        _gProvinceCityDistrictData = [NSJSONSerialization JSONObjectWithData:resData options:NSJSONReadingMutableLeaves error:nil];
    }
    return _gProvinceCityDistrictData;
}
//通过省市区编码获取省市区名称
- (NSString*)convertCodeToName:(NSString *)code
{
    NSString *provinceCode = nil;
    NSString *cityCode = nil;
    //    NSString *districtCode = nil;
    
    NSString *provinceText = @"";
    NSString *cityText = @"";
    NSString *districtText = @"";
    
    //省市区
    NSArray *provinceArray = [self.gProvinceCityDistrictData objectAtIndex:0];
    NSDictionary *citysDic = [self.gProvinceCityDistrictData objectAtIndex:1];
    NSDictionary *countysDic = [self.gProvinceCityDistrictData objectAtIndex:2];
    
    //先遍历区
    BOOL findDestrict = NO;
    NSArray *countysKeys = [countysDic allKeys];
    for (int i = 0; i < countysKeys.count; ++i) {
        NSString *cityKey = [countysKeys objectAtIndex:i];
        NSArray *countysArray = [countysDic objectForKey:cityKey];
        //遍历每个key下的所有区code，区code一致时，城市code就是key
        for (NSDictionary *countyDic in countysArray) {
            if ([[countyDic objectForKey:@"code"] isEqualToString:code]) {
                districtText = [countyDic objectForKey:@"name"];
                cityCode = cityKey;
                findDestrict = YES;
                break;
            }
        }
        if (findDestrict) {
            break;
        }
    }
    //如果没找到区:通过code直接在市里面寻找
    if (!cityCode) {
        cityCode = code;
    }
    BOOL findCity = NO;
    NSArray *citysKeys = [citysDic allKeys];
    for (int i = 0; i < citysKeys.count; ++i) {
        NSString *provinceKey = [citysKeys objectAtIndex:i];
        NSArray *citysArray = [citysDic objectForKey:provinceKey];
        //遍历每个key下的所有市code，市code一致时，省code就是key
        for (NSDictionary *cityDic in citysArray) {
            if ([[cityDic objectForKey:@"code"] isEqualToString:cityCode]) {
                cityText = [cityDic objectForKey:@"name"];
                provinceCode = provinceKey;
                findCity = YES;
                break;
            }
        }
        if (findCity) {
            break;
        }
    }
    //没有找到市：通过code直接在省里面找
    if (!provinceCode) {
        provinceCode = code;
    }
    for (NSDictionary *dic in provinceArray) {
        if ([[dic objectForKey:@"code"] isEqualToString:provinceCode]) {
            provinceText = [dic objectForKey:@"name"];
            break;
        }
    }
    return [NSString stringWithFormat:@"%@%@%@",provinceText,cityText,districtText];
}


#pragma mark - 缓存相关
+ (void)cleanCache
{
    //NSString *extension = @"plist";
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        
        /*
         两种计算缓存方式
         方式1 清除该app的documentsDirectory目录下所以缓存文件大小
         方式2 清除该app的plist后缀、default后缀以及SDWebImageCache文件夹下总共的缓存大小
         */
        //方式1
        NSError *err;
        [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:&err];
        NSLog(@"file deleted");
        if (err) {
            NSLog(@"file remove error, %@", err.localizedDescription );
        }
        
        //方式2
        //        if (([[filename pathExtension] isEqualToString:@"plist"]) || [filename isEqualToString:@"com.hackemist.SDWebImageCache.default"] || [filename isEqualToString:@"default"]) {
        //
        //            [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
        //        }
    }
}
//计算程序缓存大小
+ (float)calculateCache
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
    long long cacheSize = 0;
    
    //只计算.plist文件和SDImageCache
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        
        
        
        /*
         两种计算缓存方式
         方式1 计算该app的documentsDirectory目录下所以缓存文件大小
         方式2 计算该app的plist后缀、default后缀以及SDWebImageCache文件夹下总共的缓存大小
         */
        //方式1
        NSString *fileAllName = [documentsDirectory stringByAppendingPathComponent:filename];
        cacheSize += [fileManager attributesOfItemAtPath:fileAllName error:nil].fileSize;
        long long allSize = 0;
        [DataService fileSizeForDir:fileAllName allSize:&allSize];
        cacheSize += allSize;
        
        //方式2
        //        if (([[filename pathExtension] isEqualToString:@"plist"]) || [filename isEqualToString:@"com.hackemist.SDWebImageCache.default"] || [filename isEqualToString:@"default"]) {
        //            NSString *fileAllName = [documentsDirectory stringByAppendingPathComponent:filename];
        //            cacheSize += [fileManager attributesOfItemAtPath:fileAllName error:nil].fileSize;
        //
        //            //图片缓存文件夹
        //            if ([filename isEqualToString:@"com.hackemist.SDWebImageCache.default"]) {
        //                NSString *dirfile;
        //                NSDirectoryEnumerator *dirEnum = [[NSFileManager defaultManager] enumeratorAtPath:fileAllName];
        //                while ((dirfile = [dirEnum nextObject]))
        //                {
        //                    BOOL isDir;
        //                    NSString *fileNameInDir = [fileAllName stringByAppendingPathComponent:dirfile];
        //                    [[NSFileManager defaultManager] fileExistsAtPath:fileNameInDir isDirectory: &isDir];
        //                    if (!isDir) {
        //                        cacheSize += [fileManager attributesOfItemAtPath:fileNameInDir error:nil].fileSize;
        //                    }
        //                }
        //            }
        //            //读取default文件夹
        //            if ([filename isEqualToString:@"default"]) {
        //                long long allSize = 0;
        //
        //                [DataService fileSizeForDir:fileAllName allSize:&allSize];
        //                cacheSize += allSize;
        //            }
        //        }
    }
    //    NSLog(@"%fM",[self folderSizeAtPath:[documentsDirectory stringByAppendingPathComponent:filename]]);
    return (float)cacheSize/(1024.0*1024.0);
}

//+ (float)folderSizeAtPath2222{
//
//
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
//    NSString *documentsDirectory = [paths objectAtIndex:0];
//    NSString *filename;
//    NSString *path = [documentsDirectory stringByAppendingPathComponent:filename];
//
//    NSFileManager *fileManager = [NSFileManager defaultManager]; //创建文件管理器
//
//    NSDirectoryEnumerator *dir = [fileManager enumeratorAtPath:path]; // 获取目录下的文件
//
//    CGFloat size_file = 0;
//
//    //遍历目录下的文件
//
//    while ([dir nextObject]) {
//
//        size_file += [dir.fileAttributes[@"NSFileSize"] longLongValue];//获取缓存文件大小
//
//    }
//
//    return (float)size_file/(1024.0*1024.0);
//
//}

//计算文件夹size
+(void)fileSizeForDir:(NSString*)path allSize:(long long *)allSize
{
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    
    NSArray* array = [fileManager contentsOfDirectoryAtPath:path error:nil];
    for(int i = 0; i<[array count]; i++)
    {
        NSString *fullPath = [path stringByAppendingPathComponent:[array objectAtIndex:i]];
        
        BOOL isDir;
        if ( !([fileManager fileExistsAtPath:fullPath isDirectory:&isDir] && isDir) )
        {
            NSDictionary *fileAttributeDic=[fileManager attributesOfItemAtPath:fullPath error:nil];
            //size+= fileAttributeDic.fileSize;
            *allSize += fileAttributeDic.fileSize;
        }
        else
        {
            [self fileSizeForDir:fullPath allSize:allSize];
        }
    }
    //return size;
}

+ (float)fileSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:path]){
        
        long long size = [fileManager attributesOfItemAtPath:path error:nil].fileSize;
        // 返回值是字节 B K M
        return size/(1024.0*1024.0);
    }
    return 0;
}
//计算目录大小
+ (float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    float folderSize;
    if ([fileManager fileExistsAtPath:path]) {
        NSArray *childerFiles=[fileManager subpathsAtPath:path];
        for (NSString *fileName in childerFiles) {
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            // 计算单个文件大小
            folderSize += [DataService fileSizeAtPath:absolutePath];
        }
        //SDWebImage框架自身计算缓存的实现
        // folderSize+=[[SDImageCache sharedImageCache] getSize]/1024.0/1024.0;
        return folderSize;
    }
    return 0;
}

+ (NSArray *)getCategories:(NSString*)categoriesType
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *fileName = [NSString stringWithFormat:@"%@/%@_categories.plist",documentsDirectory,categoriesType];
    
    NSArray *categories = [NSArray arrayWithContentsOfFile:fileName];
    
    return categories;
}

+ (void)saveCategories:(NSArray *)categories categoriesType:(NSString*)categoriesType
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *fileName = [NSString stringWithFormat:@"%@/%@_categories.plist",documentsDirectory,categoriesType];
    
    [categories writeToFile:fileName atomically:YES];
}

//手机号码验证
- (BOOL)isValidateMobile:(NSString *)mobile
{
    /*
     //手机号以13， 15，18开头，八个 \d 数字字符
     NSString *phoneRegex = @"^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,0-9]))\\d{8}$";
     NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
     //    NSLog(@"phoneTest is %@",phoneTest);
     return [phoneTest evaluateWithObject:mobile];
     */
    [NSCharacterSet decimalDigitCharacterSet];
    if ([mobile stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]].length > 0) {
        return NO;
    }
    else{
        return YES;
    }
}
//邮政编码验证
- (BOOL)isValidPostcode:(NSString *)postcode
{
    NSString *phoneRegex = @"\\d{6}";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    NSLog(@"phoneTest is %@",phoneTest);
    return [phoneTest evaluateWithObject:postcode];
}

/*
 *  获取html模板正则表达式
 *
 *  用于进入新闻详情页时，用服务端的数据填充html模板中的数据
 *
 *  @return html模板正则表达式
 */
+ (NSString *)getHtmlRegex
{
    return @"<!--\\$\\{([\\d\\w_]+)\\}-->";
}

- (void)dealloc{
    
}

#pragma mark - 字体相关
//新闻字体大小
+ (UIFont *)newsFont {
    return [UIFont systemFontOfSize:[self deviceCompatibleNums:17 ip5:17 ip6:19 ip6p:20]];
}

+ (UIFont *)newsMenuFont {
    
    return [UIFont systemFontOfSize:[self deviceCompatibleNums:17 ip5:17 ip6:18 ip6p:20]];
}

+(float)deviceCompatibleNums:(float)ip4s ip5:(float)ip5 ip6:(float)ip6 ip6p:(float)ip6p{
    if (ssiPhone6 || ssiPhoneX || ssiPhoneXR) {
        return ip6;
    } else if (ssiPhone6plus || ssiPhoneXP) {
        return ip6p;
    } else if (ssiPhone5) {
        return ip5;
    }else{
        return ip4s;
    }
    
    
}

+(float)GetNavMaxTitleLength
{
    return [self deviceCompatibleNums:8 ip6:8 ip6p:8 ipX:8];
}

+(float)deviceCompatibleNums:(float)ip5 ip6:(float)ip6 ip6p:(float)ip6p ipX:(float)ipX{
    if (ssiPhone6) {
        return ip6;
    } else if (ssiPhone6plus) {
        return ip6p;
    } else if (ssiPhone5) {
        return ip5;
    }else{
        return ipX;
    }
}

+(float)deviceCompatibleNumsWithScale:(float)num{
    return num*SCREEN_W/375.0;
}

/**
 *  根据当前设备是否是iPhoneX返回状态栏值
 *  @return 等比返回
 */
+(float)GetStatusBarHeight
{
    if (ssiPhoneX) {
        return 44;
    }
    return 20;
}

/**
 *  根据当前设备是否是iPhoneX返回底部安全栏值
 *  @return 等比返回
 */

+(float)GetStatusBottomHeight{
    if (ssiPhoneX) {
        return 34;
    }
    return 0;
}

+(CGFloat)GetIphone5HeightFloat:(int)n{
    
    if (ssiPhone4) {
        return n;
    }
    
    CGFloat temp = (n*1.0/568)*SCREEN_H;
    //    CGFloat myFloat = temp*1.0/2;
    return temp;
}

+(CGFloat)GetIphone5WidthFloat:(int)n{
    if (ssiPhone4) {
        return n;
    }
    
    CGFloat temp = (n*1.0/320)*SCREEN_W;
    //    CGFloat myFloat = temp*1.0/2;
    return temp;
}

+ (UIImage *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    while (data.length > maxLength && compression > 0) {
        compression -= 0.02;
        data = UIImageJPEGRepresentation(image, compression); // When compression less than a value, this code dose not work
    }
    
    UIImage *newImage = [UIImage imageWithData:data];
    return newImage;
}


+(NSString *)CutOutStringFromStr:(NSString *)str
{
    NSString *reslutStr = str;
    float length = [DataService deviceCompatibleNums:10 ip5:10 ip6:14 ip6p:17];
    if (str.length > length) {
        reslutStr = [NSString stringWithFormat:@"%@...",[str substringToIndex:length]];//截取
    }
    return reslutStr;
}

//输入的日期字符串形如：@"1992-05-21 13:08:08"
- (NSDate *)dateFromString:(NSString *)dateString{
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:@"yyyy-MM-dd"];
    NSDate *fromdate=[format dateFromString:dateString];
    
    //注意:这里获取的时间要通过时区然后再转换为NSDate，不然转换为NSDate后和获取的字符串类型的日期 不一样
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *returnDate = [fromdate  dateByAddingTimeInterval: frominterval];
    NSLog(@"returnDate=%@",returnDate);
    return returnDate;
}

- (NSUInteger )getDay:(NSString *)fromDate systemTime:(NSString *)toDate
{
    
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents    * comp = [calendar components:NSCalendarUnitDay
                                             fromDate:[self dateFromString:fromDate]
                                               toDate:[self dateFromString:toDate]
                                              options:NSCalendarWrapComponents];
    NSLog(@" -- >>  comp : %@  << --",comp);
    //    return comp.day;
    return labs(comp.day) + 1;  //两个日期相差天数需要+1
}


//输入的日期字符串形如：@"1992-05-21 13:08:08"
+ (NSDate *)dateFromString:(NSString *)dateString format:(NSString *)myformat{
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    [format setDateFormat:myformat];
    NSDate *fromdate=[format dateFromString:dateString];
    
    //注意:这里获取的时间要通过时区然后再转换为NSDate，不然转换为NSDate后和获取的字符串类型的日期 不一样
    NSTimeZone *fromzone = [NSTimeZone systemTimeZone];
    NSInteger frominterval = [fromzone secondsFromGMTForDate: fromdate];
    NSDate *returnDate = [fromdate  dateByAddingTimeInterval: frominterval];
    NSLog(@"returnDate=%@",returnDate);
    return returnDate;
}


/**
 *计算两个时间相差天数
 */
- (NSInteger)getDifferDay:(NSString *)earlyDate withLaterDate:(NSString *)LaterDate
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    
    NSDateComponents    * comp = [calendar components:NSCalendarUnitDay
                                             fromDate:[self dateFromString:earlyDate]
                                               toDate:[self dateFromString:LaterDate]
                                              options:NSCalendarWrapComponents];
    NSLog(@" -- >>  comp : %@  << --",comp);
    return comp.day;
    //    return labs(comp.day) + 1;  //两个日期相差天数需要+1
}

/**
 * 计算两个时间相差月份数
 */
- (NSInteger)getDifferMonth:(NSDate*)earlyDate withLaterDate:(NSDate*)laterDate
{
    //    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    //    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    [gregorian setFirstWeekday:2];
    //    NSDate *fromDate = [formatter dateFromString:earlyDate];
    //    NSDate *toDate = [formatter dateFromString:laterDate];
    NSDateComponents *components = [gregorian components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:earlyDate toDate:laterDate options:0];
    NSInteger year = components.year;
    NSInteger month = components.month;
    NSInteger day = components.day;
    
    NSInteger month_num = 0;
    if (year > 0) {
        month_num += 12*year;
    }
    if (month > 0) {
        month_num += month;
    }
    if (day > 0) {
        //此时算的月份差小于实际差(比如2018-10-21和2018-11-4比较时 month=0而day=13)
        month_num += 1;
    }
    return month_num;
}


- (NSString *)getPreviousDayFromDate:(NSString *)currentDay
{
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:[DataService dateFromString:currentDay]];//前一天
    NSString *current_time = [DataService dateToString:lastDay format:@"yyyy-MM-dd"];
    return current_time;
}

- (NSString *)getPreviousDateFromDate:(NSString *)currentMonth withMonth:(int)month{
    
    NSDateComponents *comps = [[NSDateComponents alloc]init];
    [comps setMonth:month];
    NSCalendar *calendar = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *mdate = [calendar dateByAddingComponents:comps toDate:[[DataService sharedService] dateFromString:currentMonth] options:0];
    return [DataService dateToString:mdate format:@"yyyy-MM"];
}

//检验获取的网络时间是否正确(当网络慢的时候返回的是1970-01-01 00:00:00 +0000)
- (NSDate *)CheckInternetTimeIsOk:(NSDate *)date
{
    NSString *timeStr = [DataService dateToString:date format:@"YYYY-MM-DD"];
    if ([timeStr isEqualToString:@"1970-01-01"]) {
        //网络时间获取错误，此时获取本地手机时间
        date = [NSDate date];
    }
    return date;
}

- (void)SaveCurrentDayToLocal
{
    //    NSCalendar *gregorian = [[NSCalendar alloc]initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    // 获取当前日期
    NSDate* dt = [DataService getInternetDate];
    //由于获取的网络时间是当前真正时间([NSDate date]获取的时间有8小时时差，但是在转换字符串时会自动修正，因此此处由于多了8小时 需要减去)
    dt = [NSDate dateWithTimeInterval:-8*60*60 sinceDate:dt];
    
    //检验网络时间是否正确
    dt = [self CheckInternetTimeIsOk:dt];
    
    //    //修正当前日期的八个小时时差
    //    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    //    NSInteger interval = [zone secondsFromGMTForDate:dt];
    //    dt = [dt  dateByAddingTimeInterval:interval];
    //
    //    //定义一个时间字段的旗标，指定将会获取指定年、月、日、时、分、秒的信息
    //    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | kCFCalendarUnitDay;
    //    //获取不同时间字段的信息
    //    NSDateComponents* comp = [gregorian components: unitFlags fromDate:dt];
    //    NSString *YM = [NSString stringWithFormat:@"%ld-%ld",(long)comp.year,(long)comp.month];
    //    NSString *YMD = [NSString stringWithFormat:@"%ld-%ld-%ld",(long)comp.year,(long)comp.month,(long)comp.day];
    NSString *YearDay = [DataService dateToString:dt format:@"yyyy/MM"];
    NSString *YM = [DataService dateToString:dt format:@"yyyy-MM"];
    NSString *YMD = [DataService dateToString:dt format:@"yyyy-MM-dd"];
    NSString *Hour = [DataService dateToString:dt format:@"HH:mm"];
    
    NSUDSetValueWithKey(YearDay,@"Month/");
    NSUDSetValueWithKey(YM,@"Month");
    NSUDSetValueWithKey(YMD,@"Day");
    NSUDSetValueWithKey(Hour,@"Hour");
}

- (float)CountStarNum:(float)num
{
    if (num <= 3) {
        num = 0;
    }else if (num >= 3 && num <= 7) {
        num = 0.5;
    }else if (num > 7 && num < 10) {
        num = 1.0;
    }
    return num;
}

//获取Window当前显示的ViewController
- (UIViewController*)currentViewController{
    //获得当前活动窗口的根视图
    UIViewController* vc = [UIApplication sharedApplication].keyWindow.rootViewController;
    //根据不同的页面切换方式，逐步取得最上层的viewController
    if ([vc isKindOfClass:[UITabBarController class]]) {
        vc = ((UITabBarController*)vc).selectedViewController;
    }
    if ([vc isKindOfClass:[UINavigationController class]]) {
        vc = ((UINavigationController*)vc).visibleViewController;
    }
    if (vc.presentedViewController) {
        vc = vc.presentedViewController;
    }
    return vc;
}

+ (NSDate *)getInternetDate
{
    NSString *urlString = @"http://m.baidu.com";
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString: urlString]];
    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
    [request setTimeoutInterval:2];
    [request setHTTPShouldHandleCookies:FALSE];
    [request setHTTPMethod:@"GET"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    
    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
    date = [date substringFromIndex:5];
    date = [date substringToIndex:[date length]-4];
    NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
    dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
    NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: netDate];
    NSDate *localeDate = [netDate  dateByAddingTimeInterval: interval];
    return localeDate;
}
+ (void)loginoutSuccess
{
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"Token"];
    [userDefaults removeObjectForKey:@"name"];
    [userDefaults removeObjectForKey:@"is_family"];
    
    NSDictionary *dict = [userDefaults dictionaryRepresentation];
    for (NSString *key in [dict allKeys]) {
        if (([key containsString:@"201"] || [key containsString:@"202"]) && ![key containsString:NSUDGetValueWithKey(@"Day")]) {
            //今日存储的标记不移除
            [userDefaults removeObjectForKey:key];
        }
    }
    [userDefaults synchronize];
}
+ (NSDateComponents *)CheckNowTimeToStartTime:(NSString *)Time1 AndTime2:(NSString *)Time2{
    // 1.将时间转换为date
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"HH:mm";
    NSDate *date1 = [formatter dateFromString:Time1];
    NSDate *date2 = [formatter dateFromString:Time2];
    // 2.创建日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSCalendarUnit type = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 3.利用日历对象比较两个时间的差值
    NSDateComponents *cmps = [calendar components:type fromDate:date1 toDate:date2 options:0];
    // 4.输出结果
    NSLog(@"两个时间相差%ld年%ld月%ld日%ld小时%ld分钟%ld秒", cmps.year, cmps.month, cmps.day, cmps.hour, cmps.minute, cmps.second);
    return cmps;
}
@end
